<template>
  <div>
    <el-card>
      <el-table :data="cart" style="width: 100%">
        <el-table-column
          prop="name"
          label="商品名称"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="price"
          label="价格"
          width="180"
        ></el-table-column>
        <el-table-column label="数量"  prop="num">
          <template v-slot="scope">
            <el-input-number
              v-model="scope.row.num"
              :min="1"
              :max="99"
              @change="updateTotalPrice()"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button @click="removeFromCart(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row :gutter="20">
        <el-col :span="12">总价: {{ totalPrice }}</el-col>
        <el-col :span="12">
          <el-button type="primary">合并付款</el-button></el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cart: [],  //购物车数据
      totalPrice:0
    };
  },
  components: {},
  methods: {
    //移除一条数据
    removeFromCart(row){
       const index = this.cart.findIndex(item => item.id === row.id);
      if (index !== -1) {
        this.cart.splice(index, 1);
        //重新计算价格
        this.caclPrice()
        //更新缓存数据
          localStorage.setItem("carList", JSON.stringify(this.cart));
      }
    },
    //重新计算价格的方法：
    caclPrice(){
       var sum=0
           for (let index = 0; index <  this.cart .length; index++) {
            const element =  this.cart [index];
            sum+=element.price * element.num;
           } 
           this.totalPrice=sum;
    },
    updateTotalPrice(){
      console.log(11)
      //重新计算价格
      this.caclPrice()
      //更新缓存
      localStorage.setItem("carList", JSON.stringify(this.cart));
    }
  },
  
  mounted() {
       if (localStorage.getItem("carList")) {
           this.cart = JSON.parse(localStorage.getItem("carList"));
           //初次加载需要计算价格
           var sum=0
           for (let index = 0; index <  this.cart .length; index++) {
            const element =  this.cart [index];
            sum+=element.price * element.num;
           } 
           this.totalPrice=sum;
       }
       
  },
};
</script>

<style  >
</style>